package org.f0rb.core.web;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * Description goes here.
 *
 * @author yuanzhen
 * @version 1.0, 2012-02-02
 */
@SuppressWarnings("unused")
public final class WebContext {

    private WebContext() {}

	static ThreadLocal<Map<String, Object>> webContext = new ThreadLocal<Map<String, Object>>();

	public static final String HTTP_SESSION = "WebContext.HttpSession";

	public static final String HTTP_REQUEST = "WebContext.HttpServletRequest";

	public static final String HTTP_RESPONSE = "WebContext.HttpServletResponse";

	public static final String SERVLET_CONTEXT = "WebContext.ServletContext";

	public static final String APP_USER = "WebContext.AppUser";

	private synchronized static Map<String, Object> getContext() {
		Map<String, Object> map = webContext.get();
		if (map == null) {
			map = new HashMap<>();
			webContext.set(map);
		}
		return map;
	}

	/**
	 * Sets the HTTP servlet request object.
	 *
	 * @param request the HTTP servlet request object.
	 */
	public static void setRequest(HttpServletRequest request) {
		getContext().put(HTTP_REQUEST, request);
	}

	/**
	 * Gets the HTTP servlet request object.
	 *
	 * @return the HTTP servlet request object.
	 */
	public static HttpServletRequest getRequest() {
		return (HttpServletRequest) getContext().get(HTTP_REQUEST);
	}

	/**
	 * Sets the HTTP servlet response object.
	 *
	 * @param response the HTTP servlet response object.
	 */
	public static void setResponse(HttpServletResponse response) {
		getContext().put(HTTP_RESPONSE, response);
	}

	/**
	 * Gets the HTTP servlet response object.
	 *
	 * @return the HTTP servlet response object.
	 */
	public static HttpServletResponse getResponse() {
		return (HttpServletResponse) getContext().get(HTTP_RESPONSE);
	}

	/**
	 * Gets the servlet context.
	 *
	 * @return the servlet context.
	 */
	public static ServletContext getServletContext() {
		return (ServletContext) getContext().get(SERVLET_CONTEXT);
	}

	/**
	 * Sets the current servlet context object
	 *
	 * @param servletContext The servlet context to use
	 */
	public static void setServletContext(ServletContext servletContext) {
		getContext().put(SERVLET_CONTEXT, servletContext);
	}

	public static HttpSession getSession() {
		return getRequest().getSession();
	}

	public static HttpSession getSession(boolean create) {
		return getRequest().getSession(create);
	}

    public static Object getLoginUser() {
        return getSession().getAttribute(APP_USER);
    }

    public static void removeLoginUser() {
        getSession().removeAttribute(APP_USER);
    }
}
